package com.wing.productionPlan.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.productionPlan.model.entity.ProductionTheWorkOrder;
import com.wing.productionPlan.model.request.DeviceTypeForm;
import com.wing.productionPlan.model.request.ProductionTheWorkOrderForm;
import com.wing.productionPlan.model.response.DeviceOrWorkVo;
import com.wing.productionPlan.model.response.ProductionTheWorkOrderSearchVO;
import com.wing.productionPlan.model.response.ProductionTheWorkOrderVO;
import com.wing.productionPlan.model.response.ProductionTheWorkPrintVO;
import com.wing.productionPlan.service.ProductionProcessService;
import com.wing.productionPlan.service.ProductionTheWorkOrderService;
import com.wing.productionPlan.service.ProductionWorkOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import static com.wing.productionPlan.model.entity.ProductionTheWorkOrder.Status.sendOver;

/**
 * 报工单-Controller
 *
 * @author xiayang
 */
@Slf4j
@Validated
@Api(value = "Admin-生产报工单管理", tags = "#/productionPlan/productionTheWorkOrder")
@RestController("productionTheWorkOrderController")
@RequestMapping("productionPlan/admin/productionTheWorkOrder")
@RequiredArgsConstructor
public class ProductionTheWorkOrderController {

    private final ProductionTheWorkOrderService productionTheWorkOrderService;
    private final ProductionWorkOrderService productionWorkOrderService;
    private final ProductionProcessService productionProcessService;


    @ApiOperation(value = "查询所有生产报工单", notes = "搜索")
    @GetMapping("/list")
    public PageResult<ProductionTheWorkOrderVO> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(defaultValue = "create_time") String sort,
            @RequestParam(defaultValue = "asc") String order,
            ProductionTheWorkOrderVO productionTheWorkOrderVO
    ) {
        IPage<ProductionTheWorkOrderVO> pageList = productionTheWorkOrderService.getProductionTheWorkOrderVOPageList(productionTheWorkOrderVO, page, limit);

        List<ProductionTheWorkOrderVO> records = pageList.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            for (ProductionTheWorkOrderVO record : records) {
                //计算剩余数
                if (record.getStatus().getValue().equals(sendOver.getValue())){
                    record.setRemainderSentQuantity(0);
                }else{
                    // 报工数-送检数
                    int haveSendQuantity = record.getQualityQuantity()==null?0:record.getQualityQuantity();
                    int remainderSentQuantity = record.getWorkQuantity() - haveSendQuantity;
                    record.setRemainderSentQuantity(remainderSentQuantity);
                }

                //质检性质
                String qualityAttributes = this.productionWorkOrderService.getQualityAttributes(record.getWorkOrderId());
                record.setQualityAttributes(qualityAttributes);

                List<String> list = new ArrayList<>();
                list.add(record.getDeviceCode());
                List<DeviceTypeForm> deviceTypeFormList = this.productionProcessService.getDevicetTypeList(list);
                if (CollectionUtil.isNotEmpty(deviceTypeFormList)) {
                    record.setDeviceCode(deviceTypeFormList.get(0).getName());
                }
                String typeLies = this.productionWorkOrderService.getTypeLies(record.getWorkOrderId());
                if (StrUtil.isNotBlank(typeLies)) {
                    record.setType(typeLies);
                }
                //报工合格数
                BigDecimal numeratorBd = new BigDecimal(record.getWorkQuantity() - record.getQualifiedNoQuantity());
                //报工合格数
                record.setQualifiedQuantity(record.getWorkQuantity() - record.getQualifiedNoQuantity());
                //报工数
                if (numeratorBd.compareTo(BigDecimal.ZERO) != 0) {
                    BigDecimal workQuantity = new BigDecimal(record.getWorkQuantity());
                    // 执行除法，保留两位小数，使用四舍五入
                    BigDecimal percentage = numeratorBd.divide(workQuantity, 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
                    // 设置保留两位小数
                    BigDecimal result = percentage.setScale(2, RoundingMode.HALF_UP);
                    record.setBgOkRate(result);
                }else{
                    record.setBgOkRate(new BigDecimal("100.00"));
                }
                //样品合格数
                //送检数
                BigDecimal sendQuantity = new BigDecimal(record.getSendQuantity());
                if (sendQuantity.compareTo(BigDecimal.ZERO) != 0){
                    //送检数(分母)
                    if (numeratorBd.compareTo(BigDecimal.ZERO) != 0) {
                        //送检合格数
                        BigDecimal hgs = new BigDecimal(record.getSendQuantity() - record.getQualifiedNoQuantity());
                        // 执行除法，保留两位小数，使用四舍五入
                        BigDecimal percentage = hgs.divide(sendQuantity, 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
                        // 设置保留两位小数
                        BigDecimal result = percentage.setScale(2, RoundingMode.HALF_UP);
                        record.setYpOkRate(result);
                    }else{
                        record.setYpOkRate(new BigDecimal("100.00"));
                    }
                }else{
                    record.setYpOkRate(new BigDecimal("100.00"));
                }
            }
        }

        return new PageResult<>(pageList.getRecords(), pageList.getTotal());
    }

    @ApiOperation(value = "报工单详情", notes = "搜索")
    @GetMapping("/selectTheWorkOrderInfo")
    public JsonResult<List<ProductionTheWorkOrderVO>> selectTheWorkOrderInfo(Long id) {
        List<ProductionTheWorkOrderVO> list = new ArrayList<>();
        ProductionTheWorkOrderVO workOrderVO = productionTheWorkOrderService.selectTheWorkOrderInfo(id);
        list.add(workOrderVO);
        return JsonResult.success(list);
    }

    @ApiOperation(value = "添加生产报工单", notes = "添加")
    @PostMapping("/add")
    public JsonResult add(@Validated(ProductionTheWorkOrderForm.Add.class) @RequestBody ProductionTheWorkOrderForm productionTheWorkOrderForm) {
        if (productionTheWorkOrderForm.getWorkQuantity() == null) {
            return JsonResult.fail("报工数量必填！");
        }
        try {
            productionTheWorkOrderService.add(productionTheWorkOrderForm);
            return JsonResult.success("操作成功");
        } catch (Exception e) {
            log.error("添加生产报工单接口异常，原因是：{} ", e.getMessage(), e);
            return JsonResult.fail("操作失败:" + e.getMessage());
        }
    }

    @ApiOperation(value = "修改生产报工单（确认提交和确认接口）", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(ProductionTheWorkOrderForm.Update.class) @RequestBody ProductionTheWorkOrderForm productionTheWorkOrderForm) {
        ProductionTheWorkOrder productionTheWorkOrder = productionTheWorkOrderService.getById(productionTheWorkOrderForm.getId());
        if (productionTheWorkOrder == null) {
            return JsonResult.fail("修改失败！");
        }
        if (productionTheWorkOrderForm.getCheckStatus() != null) {
            if (productionTheWorkOrder.getStatus().getValue() != 1) {
                return JsonResult.fail("确认提交后才能确认！");
            }
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(ProductionTheWorkOrder.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(productionTheWorkOrderForm, productionTheWorkOrder, copyOptions);
        if (productionTheWorkOrderService.updateById(productionTheWorkOrder)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }


    @ApiOperation(value = "确认生产报工单（确认接口）", notes = "确认")
    @PutMapping("/audit/{id}/{status}")
    public JsonResult audit(@PathVariable("id") Long id, @PathVariable("status") String status) {
        ProductionTheWorkOrder productionTheWorkOrder = productionTheWorkOrderService.getById(id);
        switch (status) {
            case "correspond":
            case "discrepancy":
                if (productionTheWorkOrder.getCheckStatus() != null) {
                    if (productionTheWorkOrder.getStatus().getValue() != 1) {
                        return JsonResult.fail("未查询到报工单据！");
                    }
                }
                break;
            case "confirm":
                if (productionTheWorkOrder.getStatus().getValue() != 3) {
                    return JsonResult.fail("送检完成状态方可确认！");
                }
                break;
        }
        Boolean isOk =  productionTheWorkOrderService.audit(id,status);
        if (isOk) {
            return JsonResult.success("确认成功！");

        }
        return JsonResult.fail("确认失败！");
    }

    @ApiOperation(value = "批量审核生产报工单（审核接口）", notes = "批量审核")
    @PostMapping("/auditBatch")
    public JsonResult auditBatch(@RequestParam ProductionTheWorkOrderVO req) {
        List<ProductionTheWorkOrder> theWorkOrderList = (List<ProductionTheWorkOrder>) productionTheWorkOrderService.listByIds(req.getIds());
        for (ProductionTheWorkOrder theWorkOrder : theWorkOrderList) {
            if (theWorkOrder.getStatus().getValue() < 2) {
                return JsonResult.fail("【" + theWorkOrder.getCode() + "】" + "送检完成后才能确认！");
            }
           productionTheWorkOrderService.audit(theWorkOrder.getId(), req.getAuditStatus());
        }
        return JsonResult.success("审核成功！");
    }

    @ApiOperation(value = "删除生产报工单", notes = "删除")
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long productionTheWorkOrderId) {
        if (productionTheWorkOrderService.removeById(productionTheWorkOrderId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }


    @ApiOperation(value = "查看报工单详情", notes = "报工-详情")
    @GetMapping("detail/{id}")
    public JsonResult getDetailBy(@PathVariable("id") Long id) {
        ProductionTheWorkOrderSearchVO productionTheWorkOrderVO =  productionTheWorkOrderService.getDetailBy(id);
        if (ObjectUtil.isNotEmpty(productionTheWorkOrderVO)) {
            productionTheWorkOrderVO.setTypeName(MaintenanceEnum.gxTypeEmum.getNameByCode(productionTheWorkOrderVO.getType()));
            productionTheWorkOrderVO.setWorkstationNatureName(MaintenanceEnum.workstationEmum.getNameByCode(productionTheWorkOrderVO.getWorkstationNature()));
        }
        return JsonResult.success(productionTheWorkOrderVO);
    }

    @ApiOperation(value = "报工单-打印", notes = "报工单-打印")
    @GetMapping("printTheWork/{id}")
    public JsonResult printTheWork(@PathVariable("id") Long id) {
        ProductionTheWorkPrintVO printTheWork =  productionTheWorkOrderService.getPrintTheWork(id);
        if (ObjectUtil.isNotEmpty(printTheWork)) {
            printTheWork.setWorkstationNatureName(MaintenanceEnum.workstationEmum.getNameByCode(printTheWork.getWorkstationNature()));

            List<DeviceOrWorkVo> fessionlist = productionProcessService.fessionlist(null);
            List<DeviceOrWorkVo> devicelist = productionProcessService.devicelist(null);

            if (MaintenanceEnum.workstationEmum.SBGW.getCode().equals(printTheWork.getWorkstationNature())) {
                if (CollectionUtil.isNotEmpty(devicelist)) {
                    for (DeviceOrWorkVo deviceOrWorkVo : devicelist) {
                        if (deviceOrWorkVo.getId().equals(printTheWork.getGzsbId())) {
                            printTheWork.setGzsbName(deviceOrWorkVo.getDeviceName());
                        }
                    }
                }
            }else{
                if (CollectionUtil.isNotEmpty(fessionlist)) {
                    for (DeviceOrWorkVo deviceOrWorkVo : fessionlist) {
                        if (deviceOrWorkVo.getId().equals(printTheWork.getGzsbId())) {
                            printTheWork.setGzsbName(deviceOrWorkVo.getDeviceName());
                        }
                    }
                }
            }
        }
        return JsonResult.success(printTheWork);
    }
}
